﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ThinhTien.Models;
using DevExpress.Web.Mvc;

using DevExpress.Data;
using DevExpress.Data.Filtering;
using DevExpress.Data.Linq;
using DevExpress.Data.Linq.Helpers;
using ThinhTien.EF4;

namespace ThinhTien.Data.Repository
{
    public class UserRepository : BaseRepository<UserRepository>
    {
        public bool IsExisted(string userName)
        {
            var result = (from item in Database.DbInstant.Users
                          where item.UserName == userName
                          select item).Any();

            return result;
        }

        public void AddNew(UserViewModel model)
        {
            try
            {
                using (var db = new THINHTIENDBEntities())
                {
                    Guid? imageID = null;

                    if (model.Photo != null)
                    {
                        imageID = Guid.NewGuid();

                        db.Images.Add(new Image
                        {
                            ID = imageID.Value,
                            Size = model.Photo.Length,
                            Image1 = model.Photo,
                            Filename = model.UserName
                        });
                    }

                    db.Users.Add(new User()
                    {
                        ID = Guid.NewGuid(),
                        UserName = model.UserName,
                        FirstName = model.FirstName,
                        LastName = model.LastName,
                        Email = model.Email,
                        PhoneNumber = model.PhoneNumber,
                        Password = model.Password,
                        CreatedBy = model.UserID,
                        UpdatedBy = model.UserID,
                        CreatedDate = DateTime.Now,
                        ImageID = imageID,
                        IsDeleted = false,
                        UpdatedDate = DateTime.Now

                    });

                    db.SaveChanges();
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.Message, ex);
                throw ex;
            }
        }

        public void Update(UserViewModel model)
        {
            try
            {
                using (var db = new THINHTIENDBEntities())
                {
                    var user = (from item in db.Users
                                where item.ID == model.ID
                                select item).FirstOrDefault();

                    if (user != null)
                    {
                        user.FirstName = model.FirstName;
                        user.LastName = model.LastName;
                        user.PhoneNumber = model.PhoneNumber;
                        user.Password = model.Password;
                        user.UpdatedBy = model.UserID;
                        user.Email = model.Email;
                        user.UpdatedDate = DateTime.Now;
                        user.IsDeleted = false;

                        if (model.Photo != null)
                        {
                            var image = (from item in db.Images
                                         where item.ID == user.ImageID
                                         select item).FirstOrDefault();

                            if (image != null)
                            {
                                image.Image1 = model.Photo;
                            }
                            else
                            {
                                Guid imageID = Guid.NewGuid();

                                db.Images.Add(new Image
                                {
                                    ID = imageID,
                                    Size = model.Photo.Length,
                                    Image1 = model.Photo,
                                    Filename = model.UserName
                                });

                                user.ImageID = imageID;
                            }
                        }

                        db.SaveChanges();
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.Message, ex);
                throw ex;
            }
        }

        public void Delete(List<Guid> ids)
        {
            try
            {
                using (var db = new THINHTIENDBEntities())
                {
                    var users = (from item in db.Users
                                 where ids.Contains(item.ID)
                                 select item).ToList();

                    foreach (var user in users)
                    {
                        user.IsDeleted = true;
                    }

                    db.SaveChanges();
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.Message, ex);
                throw ex;
            }
        }

        public UserViewModel GetUserDetail(Guid userID)
        {
            var user = (from item in Database.DbInstant.Users
                        join image in Database.DbInstant.Images on item.ImageID equals image.ID into left_join
                        where item.ID == userID
                        from t in left_join.DefaultIfEmpty()
                        select new UserViewModel()
                        {
                            ID = item.ID,
                            UserName = item.UserName,
                            FirstName = item.FirstName,
                            LastName = item.LastName,
                            PhoneNumber = item.PhoneNumber,
                            Password = item.Password,
                            Photo = t.Image1,
                            Email = item.Email
                        }).FirstOrDefault();

            return user;
        }

        public UserInfo Login(string userName, string password)
        {
            var user = (from item in Database.DbInstant.Users
                        where item.UserName == userName && item.Password == password
                        select item).FirstOrDefault();

            if (user != null)
            {
                return new UserInfo()
                {
                    ID = user.ID,
                    Username = user.UserName
                };
            }

            return null;
        }
    }

    public static class UserBindingHandler
    {
        public static void GetDataRowCount(GridViewCustomBindingGetDataRowCountArgs e)
        {
            using (var db = new THINHTIENDBEntities())
            {
                e.DataRowCount = (from user in db.Users
                                  select user).ApplyFilter(e.FilterExpression).Count();
            }
        }

        public static void GetData(GridViewCustomBindingGetDataArgs e)
        {
            using (var db = new THINHTIENDBEntities())
            {
                var query = (from user in db.Users
                             where user.IsDeleted == false
                             select new
                             {
                                 user.ID,
                                 user.UserName,
                                 user.FirstName,
                                 user.LastName,
                                 user.Email,
                                 user.PhoneNumber,
                                 user.Password,
                                 user.UpdatedDate,
                                 user.UpdatedBy
                             }).Distinct().OrderByDescending(p => p.UpdatedDate)
                            .ApplySorting(e.State.SortedColumns)
                            .ApplyFilter(e.State.FilterExpression)
                            .Skip(e.StartDataRowIndex).Take(e.DataRowCount);

                List<UserViewModel> data = new List<UserViewModel>();
                foreach (dynamic item in query)
                {
                    data.Add(new UserViewModel()
                    {
                        ID = item.ID,
                        UserName = item.UserName,
                        FirstName = item.FirstName,
                        LastName = item.LastName,
                        FullName = item.FirstName + " " + item.LastName,
                        Email = item.Email,
                        PhoneNumber = item.PhoneNumber
                    });
                }

                if (data.Count == 0)
                {
                    data.Add(new UserViewModel()
                    {
                        ID = Guid.NewGuid()
                    });
                }

                e.Data = data;
            }
        }
    }
}
